class Node(object):
    def __init__(self, data=None):
        self.data = data
        self.next = None


class List(object):
    def __init__(self):
        self.head = Node()
        self.length = 0

    def insert(self, pos, data):
        i = 0
        assert pos >= 0 and pos <= self.length
        tmp = self.head
        # 找到插入点 pos为2的位置
# 我用的是这种方法 好理解
        while i < pos:
            tmp = tmp.next
            i += 1

        newNode = Node()
        newNode.data = data
        newNode.next = tmp.next
        tmp.next = newNode
        self.length += 1

    def append(self, data):
        self.insert(self.length, data)
    # 根据位置删除  根据数据删除
    def remove(self, pos):
        # 排除列表为空的可能
        assert pos < self.length

        tmp = self.head
        i = 0
        while i < pos:
            tmp = tmp.next
            i += 1
        # 我在纠结要不要这个判断 因为上面已经排除列表为空可能
        # 是不是相当于遍历到为空的时候结束
        # 可以用 length 为空判断吗
        if tmp.next is not None:# 老师说这种保险
             delNode = tmp.next
             # 下面 next 没有联想
             tmp.next = delNode.next
             self.length -= 1

      #取出数据
    def foreach(self):
        tmp = self.head.next
        while tmp is not None:
            # 可不可以不要 yield  直接是 tmp.data
            # 为何下面的 data 没有联想

            yield tmp.data
            tmp = tmp.next


if __name__ == "__main__":
    l = List()
    l.append(1)
    l.append(2)
    l.append(3)

    for x in l.foreach():
        print(x)

    print("Insert new data 4")
    l.insert(1, 4)
    for x in l.foreach():
        print(x)

    print("Remove the 2th element")
    l.remove(1)
    for x in l.foreach():
        print(x)















